package io.zjw.testblelib;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.net.telnet.TelnetClient;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import io.zjw.testblelib.util.HttpUtil;
import ir.mstajbakhsh.nmapandroid.NMAPUtilities;

/**
 * 扫描服务器：扫描局域网内在线的ip，端口为固定端口
 */
public class ServerUtil {

    //刷新服务器，将首次打开设置为true，并重新获取服务器
    public static void changeOpenState(Context context){
        SharedPreferences setting = context.getSharedPreferences("save.himi",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = setting.edit();
        editor.putBoolean("FIRST_TIME_START",true);
        editor.putString("SERVER_IP","");
        editor.commit();
    }

    //设置服务器
    public static String setUpServer(Context context,String env) throws Exception {
        SharedPreferences setting = context.getSharedPreferences("save.himi",Context.MODE_PRIVATE);
        boolean firstTimeStart = setting.getBoolean("FIRST_TIME_START",true);
        String serverIp = "";
        if(firstTimeStart){

            //扫描活跃的机器
            List<String> ipList = new ArrayList<>();
            List<String> resultList = new ArrayList<>();
            String localIP = getHostIp2();//获取本机IP
            if (localIP == null){
                return "" ;
            }
            String prefixIP = localIP.substring(0,localIP.lastIndexOf(".")+1);

            String pingCommand = "ping -c 3  -W 0.15 ";

            for (int i=1;i<256;i++){
                int finalI = i;
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Runtime ping = Runtime.getRuntime();
                                    String ip = prefixIP+ finalI;
                                    Process process = null;
                                    process = ping.exec(pingCommand+ip);
//                                     process = ping.exec(pingCommand+"10.113.248.3");
                                    BufferedReader successReader =new BufferedReader(new InputStreamReader(process.getInputStream()));
                                    boolean b = true;
                                    while(b){
                                        String line = successReader.readLine();
//                                        Log.i("line---",line);
                                        if (line !=null){
                                            if(line.contains("TTL")||line.contains("ttl")){
                                                ipList.add(ip);
                                            }
                                        }else{
                                            b=false;
                                        }
                                    }
                                    ping.freeMemory();
                                    process.destroy();
                                }catch (Exception e ){
                                    e.printStackTrace();
                                }
                            }
                        }
                ).start();

            }

            Thread.sleep(5000);
//            System.out.println("ipList.Size----"+ipList.size());
            if(ipList.size()>0){
                CountDownLatch countDownLatch = new CountDownLatch(ipList.size());
                ExecutorService executor = Executors.newFixedThreadPool(ipList.size());
                final List<Future> threadList = new ArrayList<Future>();
                for (int i= ipList.size()-1;i>=0;i--) {
                        String ipStr = ipList.get(i);
                        try {
                            Future future = executor.submit(new Runnable(){
                                @Override
                                public void run() {
                                    try {
//                                        System.out.println(Thread.currentThread().getName() + ",子行程开始执行。。。"+ipStr);
                                        int port = 8082;
                                        if(env.equals("ZB")){
                                            port = 8081;
                                        } else if (env.equals("KJB")) {
                                            port = 8086;
                                        } else if (env.equals("ccy")) {
                                            port = 8109;
                                        }
                                        //计数器减1
                                        boolean isportUsefal = isPortUseful2(ipStr,port,100,env);
                                        if (isportUsefal){
                                            resultList.add(ipStr);
                                        }
//                                        System.out.println(Thread.currentThread().getName() + ",子行程执行结束。。。");
                                    } catch (Exception e) {countDownLatch.countDown();
                                        // TODO: handle exception
                                    } finally {
                                        countDownLatch.countDown();
                                    }
                                }

                            });
                        }catch (Exception e){
//                            e.printStackTrace();
                        }
                }
                for(Future future:threadList){
                    final Future futureTemp = future;
                    Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                futureTemp.get(500, TimeUnit.MILLISECONDS);
                            } catch (InterruptedException e) {
                                futureTemp.cancel(true);
                            } catch (ExecutionException e) {
                                futureTemp.cancel(true);
                            } catch (TimeoutException e) {
                                futureTemp.cancel(true);
                            }
                        }
                    });
                    t.start();
                }

                countDownLatch.await(5000, TimeUnit.MILLISECONDS);

                if (resultList.size()>0){
                    serverIp=resultList.get(0);
                    SharedPreferences.Editor editor = setting.edit();
                    editor.putBoolean("FIRST_TIME_START",false);
                    editor.putString("SERVER_IP",serverIp);
                    editor.commit();
                }
            }

        }else{
            serverIp = setting.getString("SERVER_IP","");
        }
        return serverIp;
    }
        public  static String getHostIp2(){
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                    {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address))
                        {
//                            System.out.println("LocalhostIP:"+inetAddress.getHostAddress().toString());
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            }
            catch (SocketException ex){
                ex.printStackTrace();
            }
            return null;

        }

    /**
     * 验证此host和port是否对应畅通的后台服务
     * @param host
     * @param port
     * @param timeOut
     * @return
     */
    public static boolean isPortUseful2(String host, Integer port, Integer timeOut,String env)  {
        boolean result = false;
        String url = "http://"+host+":"+port+"/device/hello";
        if(env.equals("KJB")){
            url = "http://"+host+":"+port+"/v1/user/hello";
        }
//        System.out.println("url-------"+url);
        String flag = HttpUtil.httpGet(url);
//        System.out.println("host"+host+"response000000000000000"+jsonObject);
        if(flag.equals("hello")){
            result = true;
        }
        return result;
    }
}
